namespace TwitterButtler
{
	#region #using Directives

	using System.ComponentModel.Composition;
	using System.ComponentModel.Composition.Hosting;
	using System.Diagnostics;
	using System.IO;
	using System.Linq;
	using System.Reflection;
	using System.Windows;

	using Infrastructure;

	using ViewModels;

	#endregion

	public class Bootstrapper
	{
		private readonly TimelineWatcher timelineWatcher;
		private readonly TwitterButtlerViewModel viewModel;
		private CompositionContainer container;

		public Bootstrapper()
		{
			this.timelineWatcher = new TimelineWatcher();
			this.viewModel = new TwitterButtlerViewModel(this.timelineWatcher);
		}

		internal TwitterButtlerViewModel ViewModel
		{
			[DebuggerStepThrough]
			get { return this.viewModel; }
		}

		public bool Compose()
		{
			var aggregateCatalog = new AggregateCatalog();
			string binFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

			aggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(IButtlerRequestServer).Assembly));
			aggregateCatalog.Catalogs.Add(new DirectoryCatalog(binFolder));

			Debug.Assert(aggregateCatalog.Parts.Any());

			this.container = new CompositionContainer(aggregateCatalog);

			var batch = new CompositionBatch();
			batch.AddPart(this.timelineWatcher);
			batch.AddExportedValue<ICompositionService>(this.container);

			try
			{
				this.container.Compose(batch);
			}
			catch (CompositionException compositionException)
			{
				MessageBox.Show(compositionException.ToString());
				return false;
			}

			return true;
		}
	}
}